package com.dish.dao;

import java.util.ArrayList;
import com.dish.bean.MyUsers;
import com.dish.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDAOImpl extends BaseDAO implements UserDAO {

	@Override
	public ArrayList<MyUsers> findUsers() {
		String sql = "select userid Userid,username "
				+ "Username,password Password from users";
		return findObjs(sql,null,MyUsers.class);
	}

	@Override
	public boolean findUser(MyUsers user) {
		String sql = "select userid Userid,username "
				+ "Username,password Password from "
				+ "users where username=? and password=md5(?)";
		Object[] params = {user.getUsername(),user.getPassword()};
		if(findObj(sql,params,MyUsers.class) != null){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public int insertUser(MyUsers user) {
		String sql = "insert into users(username,password,createdate,phonenumber) values(?,md5(?),now(),?)";
		Object[] params = {user.getUsername(),user.getPassword(),user.getPhonenumber()};
		return modifyObj(sql, params);
	}

	@Override
	public int updateUser(MyUsers user) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int deleteUser(MyUsers user) {
		String sql = "delete from users where userid=?";
		Object[] params = {user.getUserid()};
		return modifyObj(sql, params);
	}
	public ArrayList<MyUsers> findAllUsers() throws Exception{
		ArrayList<MyUsers> lst = new ArrayList<MyUsers>();
		Connection conn = null;
		PreparedStatement ps =null;
		ResultSet rs = null;
		try {
			conn = JDBCUtils.getConnection();
			ps = conn.prepareStatement("select * from users");
			rs = ps.executeQuery();
			while(rs != null && rs.next()) {
				MyUsers usr = new MyUsers();
				usr.setUserid(rs.getInt("userid"));
				usr.setUsername(rs.getString("username"));
				usr.setCreatedate(rs.getTimestamp("createdate"));
				lst.add(usr);
			}
			return lst;
		}catch(RuntimeException e) {
			e.printStackTrace();
			return null;
		}finally {
			JDBCUtils.free(rs, ps, conn);
		}
	}

}
